﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using CarsRegistrationMobile.Managers;
using Microsoft.Phone.Tasks;
using CarsRegistrationMobile.Models.JSON;
using CarsRegistrationMobile.ViewModels;
using System.Windows.Media.Imaging;
using System.IO;

namespace CarsRegistrationMobile.Views
{
    public partial class Request : PhoneApplicationPage
    {
        #region State

        private PhotoChooserTask photoChooser;
        private List<RequestViewModel> requestModelsList;
        private List<Stream> imagesStreams;
        private Image tappedImage;
        private int? currentImageIndex;

        private NetworkManager networkManager;
        private NetworkManager NetworkManager
        {
            get
            {
                if (this.networkManager == null)
                {
                    this.networkManager = ((App)Application.Current).NetworkManager;
                }
                return this.networkManager;
            }
        }

        private string RequestID
        {
            get
            {
                string id = ((App)Application.Current).RequestID;
                return id;
            }
        }

        #endregion State

        public Request()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.requestModelsList = new List<RequestViewModel>();
            this.currentImageIndex = null;

            this.photoChooser = new PhotoChooserTask();
            this.photoChooser.ShowCamera = true;
            this.photoChooser.Completed += new EventHandler<PhotoResult>(this.ChooserCallbackCommon);
            this.imagesStreams = new List<Stream>();
        }

        private void Image_Tap(object sender, GestureEventArgs e)
        {
            this.tappedImage = (Image)sender;
            this.photoChooser.Show();
        }

        #region Callbacks

        private void RequestCallback(JsonResultBase jsonResult)
        {
            if (jsonResult == null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Ошибка");
                });
                return;
            }
            if (jsonResult.ResultCode != 0)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(jsonResult.Result);
                });
                return;
            }
        }

        private void ChooserCallbackCommon(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto != null)
            {
                var model = new RequestViewModel();
                var bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                model.Bitmap = bitmap;
                this.requestModelsList.Add(model);
                this.RequestImagesPivot.ItemsSource = new List<RequestViewModel>(this.requestModelsList);

                this.imagesStreams.Add(e.ChosenPhoto);
                if (this.imagesStreams.Count > 0)
                {
                    this.RequestImagesPivot.SelectedIndex = this.imagesStreams.Count - 1;
                }
            }
            else
            {
                Dispatcher.BeginInvoke(
                () =>
                {
                    MessageBox.Show("Ошибка при получении фотографии");
                });
            }
        }

        private void ChooserCompleteIndividual(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto != null)
            {

            }
        }

        #endregion Callbacks

        private void ButtonAddPhoto_Click(object sender, RoutedEventArgs e)
        {
            this.photoChooser.Show();
        }

        private void ImageSent(JsonResultBase jsonResult)
        {
            if (jsonResult.ResultCode == 0)
            {
                this.currentImageIndex++;
                if (this.currentImageIndex < this.imagesStreams.Count)
                {
                    bool first = this.currentImageIndex == 0;
                    bool last = this.currentImageIndex == this.imagesStreams.Count - 1;
                    Stream stream = this.imagesStreams[this.currentImageIndex.Value];
                    GotResultFromServer callback = new GotResultFromServer(this.ImageSent);
                    this.NetworkManager.BeginSendImage(this.RequestID, stream, first, last, callback);
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Заявка была успешно отправлена");
                        NavigationService.GoBack();
                    });
                }
            }
            else
            {
                bool first = this.currentImageIndex == 0;
                bool last = this.currentImageIndex == this.imagesStreams.Count - 1;
                Stream stream = this.imagesStreams[this.currentImageIndex.Value];
                GotResultFromServer callback = new GotResultFromServer(this.ImageSent);
                this.NetworkManager.BeginSendImage(this.RequestID, stream, first, last, callback);
            }
        }

        private void ApplicationBarMenuItemSend_Click(object sender, EventArgs e)
        {
            if (this.imagesStreams.Count > 0)
            {
                this.currentImageIndex = 0;
                bool last = this.imagesStreams.Count == 1;
                Stream stream = this.imagesStreams[this.currentImageIndex.Value];
                GotResultFromServer callback = new GotResultFromServer(this.ImageSent);
                this.NetworkManager.BeginSendImage(this.RequestID, stream, true, last, callback);
            }
        }

        private void ApplicationBarMenuItemDelete_Click(object sender, EventArgs e)
        {
            int index = this.RequestImagesPivot.SelectedIndex;
            this.imagesStreams.RemoveAt(index);
            this.requestModelsList.RemoveAt(index);
            this.RequestImagesPivot.ItemsSource = new List<RequestViewModel>(this.requestModelsList);
            this.RequestImagesPivot.SelectedIndex = this.requestModelsList.Count - 1;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            string message = "Хотите отменить подачу заявки?";
            string caption = "Отмена";
            var res = MessageBox.Show(message, caption, MessageBoxButton.OKCancel);
            e.Cancel = res == MessageBoxResult.Cancel;
            if (!e.Cancel)
            {
                this.NetworkManager.BeginDeleteRequest();
            }
        }
    }
}